<script setup lang="ts">
import { computed, h, onMounted, ref } from 'vue';

import { MdiSearch } from '@vben/icons';
import { preferences, usePreferences } from '@vben/preferences';

import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Button, Col, Input, message, RadioGroup, Row } from 'ant-design-vue';
import modal from 'ant-design-vue/es/modal';

import { deleteRoomTypeInfo } from '#/api';
import { BASE_ICON_URL } from '#/config';
import { useRoomList } from '#/hooks/useRoomList';
import { router } from '#/router';
// 使用 usePreferences 函数获取主题相关信息
const { isDark } = usePreferences();
const { roomList, fetchRoomList } = useRoomList();

// 计算当前主题
const theme = computed(() => {
  if (preferences.theme.mode === 'auto') {
    return isDark.value ? 'dark' : 'light';
  }
  return preferences.theme.mode;
});

const options = [
  { label: '全部', value: '0' },
  { label: '有效', value: '1' },
  { label: '隐藏', value: '2' },
];
// 房型类型
const filterType = ref<string>('1');
// 房间搜索名字
const name = ref<string | undefined>('');

// 跳转到添加房型页面
const handleAddRoom = () => {
  router.push('/info/room-info/room-info-add').catch((error) => {
    console.error('页面跳转失败:', error);
  });
};
// 跳转到房型详情页面 容易出现地址变化了 但实际页面未变化的情况
const goDedail = (id: number | string) => {
  router
    .push({
      path: '/info/room-info/room-info-details',
      query: { id },
    })
    .then(() => {
      console.warn('导航成功完成');
    })
    .catch((error) => {
      console.error('页面跳转失败:', error);
      if (error.name === 'NavigationDuplicated') {
        // 刷新页面
        window.location.reload();
      }
    });
};

const enableStatus = computed(() => {
  switch (filterType.value) {
    case '0': {
      return '';
    }
    case '1': {
      return true;
    }
    case '2': {
      return false;
    }
    default: {
      return '';
    }
  }
});

// 获取房型列表
const getList = async () => {
  try {
    const params = {
      name: name.value,
      enableStatus: enableStatus.value,
    };
    await fetchRoomList(params);
  } catch (error) {
    console.error('获取房型列表错误：', error);
  }
};

// 搜索输入框内容变化时触发搜索查询功能
const inputChange = () => {
  getList();
};

// 删除事件
const handleDelete = async (id: number | string) => {
  try {
    if (!id) {
      return;
    }
    modal.confirm({
      title: '删除提示',
      icon: h(ExclamationCircleOutlined),
      content: '确定要删除该房型吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        await deleteRoomTypeInfo({
          id,
        });
        message.success('删除成功');
        await getList();
      },
    });
  } catch (error) {
    console.error('删除房型错误：', error);
  }
};

onMounted(() => {
  getList();
});
</script>

<template>
  <div
    class="absolute bottom-0 right-0 flex h-[100%] w-[100%] flex-col overflow-hidden"
  >
    <div id="main" class="main overflow-auto p-4">
      <div class="mb-4 text-2xl font-bold">房型信息</div>
      <div class="card-box rounded-md px-3 pb-6">
        <!-- 房型操作 -->
        <div class="flex w-full flex-wrap items-start justify-between">
          <div class="flex flex-1 flex-wrap items-center p-3">
            <div class="mr-3 mt-1">
              <RadioGroup
                v-model:value="filterType"
                :options="options"
                option-type="button"
                size="large"
                @change="getList"
              />
            </div>
            <div>
              <Input
                v-model:value="name"
                :allow-clear="true"
                class="w-[300px] py-2 text-black"
                placeholder="搜索房型名称"
                @change="inputChange"
              >
                <template #prefix> <MdiSearch class="text-lg" /> </template>
              </Input>
            </div>
          </div>
          <div class="flex flex-wrap items-center py-2">
            <Button type="link" @click="handleAddRoom">添加房型</Button>
          </div>
        </div>
        <!-- 房型列表 -->
        <div>
          <Row v-if="roomList.length > 0" :wrap="true">
            <Col
              v-for="item in roomList"
              :key="item.id"
              :class="[
                theme === 'dark' ? 'hover:bg-[#777]' : 'hover:bg-gray-100',
              ]"
              :lg="24"
              :md="24"
              :sm="24"
              :xl="12"
              :xs="24"
              class="rounded-sm p-3 pb-0"
            >
              <div class="flex flex-wrap">
                <!-- 图片 -->
                <div class="relative mb-3 mr-3">
                  <div
                    :style="{ 'background-image': `url(${item.images})` }"
                    class="h-[236px] w-[158px] overflow-hidden bg-cover bg-center bg-no-repeat"
                  ></div>
                  <div
                    class="absolute bottom-0 left-0 flex h-8 w-full items-center justify-center bg-black bg-opacity-60 text-center text-white"
                  >
                    {{ item.imagesNum || 0 }}张图片
                  </div>
                </div>
                <!-- 信息 -->
                <div class="relative flex-auto">
                  <div class="text-xl font-bold">{{ item.nameZh || '' }}</div>
                  <div>
                    <p class="mt-2">
                      <span class="font-bold">床型: </span>
                      <span>
                        （{{ item.bedNum || 1 }}张{{ item.bedType || '床' }}）
                      </span>
                    </p>
                    <p class="mt-2">
                      <span class="font-bold">使用面积: </span>
                      <span>{{ item.roomArea || 0 }}㎡</span>
                    </p>
                    <p class="mt-2">
                      <span class="font-bold">楼层: </span>
                      <span>{{ item.floor || '-' }}</span>
                    </p>
                    <p class="mt-2">
                      <span class="font-bold">数量: </span>
                      <span>{{ item.roomNum || '-' }}</span>
                    </p>
                    <p class="mt-2">
                      <span class="font-bold">最多入住人数: </span>
                      <span>{{ item.maxGuests || '-' }}</span>
                    </p>
                    <p class="mt-2">
                      <span class="font-bold">最多入住成人数: </span>
                      <span>{{ item.maxAdult || '-' }}</span>
                    </p>
                    <p class="mt-2">
                      <span class="font-bold">最多入住儿童数: </span>
                      <span>{{
                        item.maxChild === -1
                          ? '未知'
                          : item.maxChild === 0
                            ? '不接待'
                            : item.maxChild
                      }}</span>
                    </p>
                  </div>
                  <div class="absolute bottom-3 right-0">
                    <Button
                      class="text-gray-600"
                      type="link"
                      @click="handleDelete(item.id)"
                    >
                      <span>删除</span>
                    </Button>
                    <Button
                      :class="[theme === 'dark' ? 'text-white' : 'text-black']"
                      class="h-auto w-auto border-gray-500 px-6 py-2"
                      @click="goDedail(item.id)"
                    >
                      <span>详情</span>
                    </Button>
                  </div>
                </div>
              </div>
            </Col>
          </Row>
          <div
            v-if="roomList.length === 0"
            class="flex flex-col items-center py-6"
          >
            <img
              :src="`${BASE_ICON_URL}no-data.png`"
              class="h-auto w-[200px]"
            />
            <div class="mt-3 text-gray-400">暂无房型，快去添加吧~</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.main {
  flex: 1;
}
</style>
